import React from 'react';
import QR from './qrcode';
const {QRErrorCorrectLevel} = QR;
const QRCodeClazz = QR.QRCode;

class QRCode extends React.Component {
    displayName = 'QRCode';

    static defaultProps = {
        render: 'canvas',
        width: 256,
        height: 256,
        typeNumber: -1,
        correctLevel: QRErrorCorrectLevel.H,
        background: '#ffffff',
        foreground: '#000000'
    }

    make () {
        const {typeNumber, correctLevel, text, width, height, foreground, background} = this.props;
        const qrcode = new QRCodeClazz(typeNumber, correctLevel);
        qrcode.addData(text);
        qrcode.make();

        console.log(this.canvas);
        
        this.canvas.width	= width;
        this.canvas.height	= height;
        const ctx = this.canvas.getContext('2d');

        const tileW	= width / qrcode.getModuleCount();
        const tileH	= height / qrcode.getModuleCount();

        // draw in the canvas
        for ( let row = 0; row < qrcode.getModuleCount(); row++ ) {
            for ( let col = 0; col < qrcode.getModuleCount(); col++ ) {
                ctx.fillStyle = qrcode.isDark(row, col) ? foreground : background;
                const w = (Math.ceil((col + 1) * tileW) - Math.floor(col * tileW));
                const h = (Math.ceil((row + 1) * tileW) - Math.floor(row * tileW));
                ctx.fillRect(Math.round(col * tileW),Math.round(row * tileH), w, h);  
            }	
        }
        return this.canvas;
    }

    componentDidMount () {
        this.make();
    }

    shouldComponentUpdate (nextProps) {
        if (this.props.background !== nextProps.background
            || this.props.text !== nextProps.text
            || this.props.foreground !== nextProps.foreground
            || this.props.width !== nextProps.width
            || this.props.height !== nextProps.height) {
            return true;
        }
        return false;
    }

    componentDidUpdate () {
        this.make();
    }

    render () {
        return <div className='cm-qrcode'>
            <canvas ref={f => this.canvas = f}/>
        </div>;
    }
}

export default QRCode;
